package com.zephyr.vchcenter.helper;

import org.hibernate.Session;
import org.jbpm.JbpmConfiguration;
import org.jbpm.JbpmContext;

public class HibernateSessionFactory {
	private static JbpmConfiguration jbpmConfiguration = JbpmConfiguration
			.getInstance();
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
	private static JbpmContext jbpmContext;
	static {
		jbpmContext = jbpmConfiguration.createJbpmContext();
	}

	private HibernateSessionFactory() {

	}

	public static Session getSession() {
		Session session = (Session) threadLocal.get();
		if (session == null || !session.isOpen()) {
			if (jbpmContext == null) {

				rebuildJbpmContext();
			}

			session = (jbpmContext != null) ? jbpmContext.getSession() : null;
			threadLocal.set(session);

		}
		return session;
	}

	public static void rebuildJbpmContext() {
		jbpmContext = jbpmConfiguration.createJbpmContext();

	}

	public static void closeSession() {
		Session session = (Session) threadLocal.get();
		threadLocal.set(null);
		if (session != null) {

			session.close();
		}

	}
}
